package org.opens.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.opens.util.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/file")
@Api(value = "minio接口", tags = {"minio接口"})
public class MinioController {

    @Autowired
    private MinioUtil minioUtil;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public ResponseEntity uploadFile(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            Boolean upload = minioUtil.upload(file, fileName);
            if (upload) {
                return ResponseEntity.ok(minioUtil.getFileUrl(fileName));
            } else {
                return ResponseEntity.status(400).body("上传失败！");
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body(e.getMessage());
        }
    }

    @ApiOperation("下载文件")
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        minioUtil.download(fileName, response);
    }

}
